package com.cg.design.depthdesign.command.commands;

import com.cg.design.depthdesign.command.editor.Editor;

/**
 * 将文字剪切到剪贴板
 *
 * @program: LeetCode->CutCommand
 * @author: cg
 * @create: 2022-04-05 18:13
 **/
public class CutCommand extends Command {

    public CutCommand(Editor editor) {
        super(editor);
    }

    /**
     * 剪切命令改变了编辑器的状态，因此它必须被保存到历史记录中。
     * <p>
     * 只要方法返回 true，它就会被保存。
     *
     * @return
     */
    @Override
    public boolean execute() {
        if (editor.textField.getSelectedText().isEmpty()) {
            return false;
        }
        backup();
        String source = editor.textField.getText();
        editor.clipboard = editor.textField.getSelectedText();
        editor.textField.setText(cutString(source));
        return true;
    }

    /**
     * 剪切选中的字符串
     *
     * @param source
     * @return
     */
    private String cutString(String source) {
        String start = source.substring(0, editor.textField.getSelectionStart());
        String end = source.substring(editor.textField.getSelectionEnd());
        return start + end;
    }

}
